<template>
  <div class="pagination">
    <button @click="$emit('addPageNo', pageNo - 1)" :disabled="pageNo === 1">
      上一页
    </button>
    <button v-if="pagerNumber.start > 1" @click="$emit('addPageNo', 1)">
      1
    </button>
    <button v-if="pagerNumber.start > 2">···</button>

    <button
      @click="$emit('addPageNo', i)"
      v-for="(i, index) in pagerNumber.end"
      :key="index"
      v-if="i >= pagerNumber.start"
      :class="{ active: i == pageNo }"
    >
      {{ i }}
    </button>

    <button v-if="pagerNumber.end < totalPage - 1">···</button>
    <button
      v-if="pagerNumber.end < totalPage"
      @click="$emit('addPageNo', totalPage)"
    >
      {{ totalPage }}
    </button>
    <button
      @click="$emit('addPageNo', pageNo + 1)"
      :disabled="pageNo === totalPage"
    >
      下一页
    </button>
    <!--下拉菜单-->
    <select
      style="width: 100px; height: 28px; text-align: center; margin: 0px 5px"
      v-model="change"
      @change="$emit('addPageSize', change)"
    >
      <option value="5">5/page</option>
      <option value="7">7/page</option>
      <option value="9">9/page</option>
      <option value="11">11/page</option>
    </select>
    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      change: 5,
    };
  },
  name: "Pagination",
  // total:数据总量  pageSize:单页显示数  pagerCount:连续页数  pageNo:当前页
  props: ["total", "pageSize", "pagerCount", "pageNo"],
  computed: {
    // 计算当前总页数
    totalPage() {
      return Math.floor(this.total / this.pageSize);
    },
    pagerNumber() {
      let { totalPage, pagerCount, pageNo } = this;
      let start = 0;
      let end = 0;

      //异常判断,当前总页数小于连续页数
      if (totalPage < pagerCount) {
        start = 1;
        end = totalPage;
      } else {
        // 正常情况
        // 记录开头和结尾的边界
        start = pageNo - Math.floor(pagerCount / 2);
        end = pageNo + Math.floor(pagerCount / 2);

        // 修正左侧
        if (start < 1) {
          start = 1;
          end = pagerCount;
        }

        //修正右侧
        if (end > totalPage) {
          start = totalPage - pagerCount + 1;
          end = totalPage;
        }
      }

      return {
        start,
        end,
      };
    },
  }
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>